package com.asap.demo.mysql.handle;


import com.asap.demo.mysql.table.JsonField;
import com.asap.demo.mysql.table.JsonTable;
import com.asap.demo.mysql.util.JsonParser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class RuleParse {
	private static final Logger logger = LoggerFactory.getLogger(RuleParse.class);

	private JsonTable tableDefine = null;
	private String tableInsertSql = "";
	private String tableQuerySql = "";
	private boolean needUpdate = false;
	private List<JsonField> updateFields = null;
	private List<JsonField> conditionFields = null;
	private JsonField primaryKeyField=null;
	private Map<String, String> configMap = null;

	public JsonField getPrimaryKeyField() {
		return primaryKeyField;
	}

	public String getTableInsertSql() {
		return tableInsertSql;
	}

	public String getTableQuerySql() {
		return tableQuerySql;
	}

	public JsonTable getTableDefine() {
		return tableDefine;
	}

	public List<JsonField> getUpdateFields() {
		return updateFields;
	}

	public List<JsonField> getConditionFields() {
		return conditionFields;
	}

	public void setConfigMap(Map<String, String> configMap) {
		this.configMap = configMap;
	}

	public boolean isNeedUpdate() {
		return needUpdate;
	}


	public void parseData(String fileName) {
		parseRule(readRule(fileName));
		formatSql();
		pareseUpdateFields();
	}

	public static String readRule(String fileName)
	{
		String data = null;
		FileInputStream fileInputStream =null;
		try{
			fileInputStream = new FileInputStream(new File(fileName));

			int readByte = 0;
			byte[] bytedata = new byte[204800];
			while(-1 != (readByte = fileInputStream.read(bytedata))){
			}

			data = new String(bytedata);
		}catch(IOException e){
			logger.error("read file error",e);
		}finally {
			if(fileInputStream!=null) {
				try {
					fileInputStream.close();
				} catch (IOException e) {
					logger.error("",e);
				}
			}
		}

		return data;
	}
	public void parseRule(String rule) {
		Map<String, Object> mapInputRule = JsonParser.<String, Object>parseFrom(rule.trim());
		tableDefine = new JsonTable();
		tableDefine.setTableName((String) mapInputRule.get("table_name"));
		tableDefine.setTopicPrimaryKey((String) mapInputRule.get("topic_primary_key"));
		tableDefine.setPrimaryKey((String) mapInputRule.get("primary_key"));
		List fieldRules = (List<Object>) mapInputRule.get("fields");
		List<JsonField> listFields = new ArrayList<JsonField>();
		for (int i = 0; i < fieldRules.size(); i++) {
			Map<Object, Object> fieldJson = (Map<Object, Object>) fieldRules.get(i);
			JsonField field = new JsonField();
			field.setDbFieldName((String) fieldJson.get("db_field_name"));
			field.setTopicFieldName((String) fieldJson.get("topic_field_name"));
			field.setFieldType((String) fieldJson.get("field_type"));
			field.setDefaultValue((String) fieldJson.get("default_value"));
			if (StringUtils.equals("true", (String) fieldJson.get("need_update"))) {
				field.setNeedUpdate(true);
			}
			if (StringUtils.equals("true", (String) fieldJson.get("is_condition"))) {
				field.setCondition(true);
			}
			if(fieldJson.containsKey("need_update_add")){
				if (StringUtils.equals("true", (String) fieldJson.get("need_update_add"))) {
					field.setNeedUpdateAdd(true);
				}
			}
			listFields.add(field);
		}
		tableDefine.setJsonFieldList(listFields);
	}


	public void formatSql() {
		// 遍历自定义配置中的所有表
		StringBuffer insertSql = new StringBuffer();
		tableQuerySql = "SELECT COUNT(*) FROM "+tableDefine.getTableName()+" WHERE " + tableDefine.getPrimaryKey();
		insertSql.append("insert into ");
		insertSql.append(tableDefine.getTableName());
		insertSql.append(" (");
		List<JsonField> fields = tableDefine.getJsonFieldList();
		int length = fields.size();
		for (int i = 0; i < length; i++) {
			insertSql.append("`").append(fields.get(i).getDbFieldName()).append("`");
			if (i < length - 1) {
				insertSql.append(",");
			}
			if(tableDefine.getPrimaryKey().equals(fields.get(i).getDbFieldName())){

				primaryKeyField = fields.get(i);
				if(fields.get(i).getFieldType().equals("string") || fields.get(i).getFieldType().equals("date")){
					tableQuerySql += "='?'";
				}else {
					tableQuerySql += "=?";
				}
			}
		}

		insertSql.append(") values(");
		for (int i = 0; i < length; i++) {
			insertSql.append("?");
			if (i < length - 1) {
				insertSql.append(",");
			}
		}

		insertSql.append(") ");
		tableInsertSql = insertSql.toString();


	}


		public void pareseUpdateFields() {
		updateFields = new ArrayList<>();
		conditionFields = new ArrayList<>();
		List<JsonField> fields = tableDefine.getJsonFieldList();

		int length = fields.size();
		for (int i = 0; i < length; i++) {
			if(fields.get(i).isNeedUpdate()){
				updateFields.add(fields.get(i));
			}

			if(fields.get(i).isCondition()){
				conditionFields.add(fields.get(i));
			}
		}

		if(!updateFields.isEmpty()){
			needUpdate = true;
		}
	}


//	public void formatUpdateSql() {
//		// 遍历自定义配置中的所有表
//
//		updateFields = new ArrayList<>();
//		conditionFields = new ArrayList<>();
//		List<JsonField> fields = tableDefine.getJsonFieldList();
//
//		int length = fields.size();
//		for (int i = 0; i < length; i++) {
//			if(fields.get(i).isNeedUpdate()){
//				updateFields.add(fields.get(i));
//			}
//
//			if(fields.get(i).isCondition()){
//				conditionFields.add(fields.get(i));
//			}
//		}
//
//		if(!updateFields.isEmpty()){
//			needUpdate = true;
//			StringBuffer updateSql = new StringBuffer();
//			updateSql.append("UPDATE ");
//			updateSql.append(tableDefine.getTableName());
//			updateSql.append(" SET ");
//			int length2 = updateFields.size();
//
//			for (int i = 0; i < length2; i++) {
//				updateSql.append("`").append(updateFields.get(i).getDbFieldName()).append("`").append("=?");
//				if (i < length2 - 1) {
//					updateSql.append(",");
//				}
//			}
//
//			if(conditionFields.isEmpty()){
//				updateSql.append(" WHERE ").append(tableDefine.getPrimaryKey()).append("=?");
//			}else {
//				updateSql.append(" WHERE ");
//				int length3 = conditionFields.size();
//				for (int j = 0; j < length3; j++) {
//					updateSql.append(conditionFields.get(j).getDbFieldName()).append("=?");
//					if (j < length3 - 1) {
//						updateSql.append(" AND ");
//					}
//				}
//			}
//
//			if(StringUtils.isEmpty(updateCondition)){
//				updateSql.append("  AND ").append(updateCondition);
//			}
//
//			tableUpdateSql = updateSql.toString();
//			tableUpdateSql = "SELECT COUNT(*) FROM "+tableDefine.getTableName()+" WHERE " + tableDefine.getPrimaryKey() + "=?";
//		}
//	}
}
